package javase_class_250906;

/**
 * ClassName: EagerSingleton
 * Package: javase_class_250906
 * Description:
 *
 * @Author harkjeans
 * @Create 2025/9/6 22:19
 * @Version 1.0
 */
/**
 * 饿汉式单例
 * 优点：线程安全，实现简单
 * 缺点：不是懒加载，类加载时就初始化，可能造成资源浪费
 */
public class EagerSingleton {
    // 1. 在类加载时就直接创建实例
    private static final EagerSingleton instance = new EagerSingleton();

    // 2. 私有化构造方法，防止外部new实例
    private EagerSingleton() {
        // 防止通过反射创建实例
        if (instance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance.");
        }
        System.out.println("EagerSingleton instance created!");
    }
    // 3. 提供全局访问点
    public static EagerSingleton getInstance() {
        return instance;
    }

    // 示例方法
    public void showMessage() {
        System.out.println("Hello from EagerSingleton!");
    }
}


